﻿using System;
using MyTinnyApi.model;

namespace MyTinnyApi.util
{
	public class    HttpUtil
	{
        public static async Task<string> SendHttpRequest(Requests req)
        {
            var url = req.FullRequestUrl;

            var method = HttpMethod.Get;
            switch (req.RequestMethod.ToLower())
            {
                case "get":

                    break;
                case "post":
                    method = HttpMethod.Post;
                    break;
                case "put":
                    method = HttpMethod.Put;
                    break;
            }

            var headers = new Dictionary<string, string>();
            if(req.RequestHeaderList?.Count > 0)
            {
                foreach (var h in req.RequestHeaderList)
                {
                    headers[h.HeaderName] = h.HeaderValue;
                }
            }

            var body = "";

            return await SendHttpRequest(url, method, headers, body);
        }

        private static async Task<string> SendHttpRequest(string url, HttpMethod method, Dictionary<string, string> headers, string body)
        {
            using (HttpClient client = new HttpClient())
            {
                // 设置请求方法
                HttpRequestMessage request = new HttpRequestMessage(method, url);

                // 设置请求头
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        request.Headers.Add(header.Key, header.Value);
                    }
                }

                // 设置请求体
                if (!string.IsNullOrEmpty(body))
                {
                    request.Content = new StringContent(body);
                }

                // 发送请求并获取响应
                HttpResponseMessage response = await client.SendAsync(request);

                // 读取响应内容
                string responseContent = await response.Content.ReadAsStringAsync();

                // 返回响应结果
                return responseContent;
            }
        }
    }
}

